
var reminderFox_upload_headless ;
function reminderFox_upload_Startup()
{
	reminderFox_upload_headless = REMINDER_FOX_UI_MODE_HEADLESS_SHOW_ALL_UI;
  	reminderFox_upload_statusTxt(reminderFox_getBundle().getString("rf.upload.ready.label"),0);
  	setTimeout(reminderFox_upload_senddata, 0);
}

function reminderFox_upload_Startup_headless(headlessLevel)
{
	  reminderFox_upload_headless = headlessLevel; 
 	 reminderFox_upload_statusTxt(reminderFox_getBundle().getString("rf.upload.ready.label"),0);
 	 setTimeout(reminderFox_upload_senddata, 0);
}

function reminderFox_upload_closeWindow() {
 	if ( window.arguments != null && window.arguments[0] != null && window.arguments[0].closeOnNoErrors == 1) {
  		close();
  	}
  	else {
  		var reminderFox_upload_button= document.getElementById("reminderFox_upload_button");
  		reminderFox_upload_button.setAttribute("label",reminderFox_getBundle().getString("rf.net.done") ); 	
  	}
}
function reminderFox_upload_senddata()
{
  var _uploadURL = "";
  var _ioService = Components.classes["@mozilla.org/network/io-service;1"]
               	   .getService(Components.interfaces.nsIIOService);

  var proto = reminderFox_prefs.getCharPref(REMINDER_FOX_PREF + "." + REMINDER_FOX_PROTO);
  var address = reminderFox_prefs.getCharPref(REMINDER_FOX_PREF + "." + REMINDER_FOX_ADDRESS);
  var _username = reminderFox_prefs.getCharPref(REMINDER_FOX_PREF + "." + REMINDER_FOX_USERNAME);
  
    if ( address == null || address.length == 0 ) {
  	  reminderFox_uploadCallback(reminderFox_getBundle().getString("rf.net.done"),-1);
  	  return;
  }
  
  
  var loginData = {
    ljURL : proto + "://" + address,
    username : _username,
    password : ''
  };

  loginData = reminderFox_getPassword(loginData);

  if (loginData == null || loginData.password == null) {
  	// no password found on password manager - user HAS TO set this password first!
    	reminderFox_uploadCallback(reminderFox_getBundle().getString("rf.upload.noPasswordSet.label"),3);
		return;
  }
  
  // uri-encode username and password
  _username = encodeURIComponent( _username );
  var _password = encodeURIComponent (loginData.password );
 	
  _uploadURL = proto + "://" + _username + ":" + _password + "@" + address;
 
  reminderFox_upload_statusTxt(reminderFox_getBundle().getString("rf.upload.exporting.label"),0);
  var i;

  
//  // safety check: if there are no events and no todo's in the local file, we will assume that this an error condition 
//  // (this happens frequently with icalx.com where the remote file gets cleared) and will not upload the local reminders
//  var hasTodos = false;  			 
//  for ( var n in reminderFoxTodosArrayArg ) {
//		var reminderFoxTodos = reminderTodos[n];
//		if (reminderFoxTodos.length > 0  ) {
//			hasTodos = true;
//			break;
//		}	  	
//  }
//  if ( reminderFoxEvents.length == 0 || !hasTodos ) {
//  		reminderFox_logMessageLevel( 
//			  			"Failed: local file has no events or todo's...", REMINDER_FOX_LOG_LEVEL_FINE);  		
//	 	return;
//  	}


  var reminderFoxEvents = reminderFox_getReminderEvents();
  var reminderFoxTodosArrayArg = reminderFox_getReminderTodos();  // iterate over all reminders
  var str=reminderFox_constructReminderOutput(reminderFoxEvents, reminderFoxTodosArrayArg, true);;
  
	
  // now clear the reminders so the Add Reminder doesn't use them (because they would have escaped commas)
  reminderFox_clearRemindersAndTodos();

  var uploadURI = _ioService.newURI(_uploadURL,null,null);
  var mimetype = "txt/xml; charset=UTF-8"; 
  if(!str)
  {
    reminderFox_uploadCallback(reminderFox_getBundle().getString("rf.net.done"),-3);
    return;
  }else if( ! gUploadService.start(str,
                                    uploadURI,
                                    mimetype,reminderFox_uploadCallback)) {

    reminderFox_uploadCallback(reminderFox_getBundle().getString("rf.net.done"),-1);
  }
}

function reminderFox_uploadCallback(aStatus,aError) {
   reminderFox_logMessageLevel(new Date() + ": Uploaded reminders...", REMINDER_FOX_LOG_LEVEL_FINE);

  if(aStatus != reminderFox_getBundle().getString("rf.net.done") && aError==0) {
    reminderFox_upload_statusTxt(aStatus,aError);
    return;
   }
  switch(aError){
    case -2:
      reminderFox_upload_statusTxt(aStatus,aError);
		if ( reminderFox_upload_headless == REMINDER_FOX_UI_MODE_HEADLESS_SHOW_ERRORS) {
			var status =   (aError)?reminderFox_upload_getErrorMsg(aError):aStatus;
			alert( reminderFox_getBundle().getString("rf.add.network.status.msg.error") + ": " + status );
  		}         
      break;
    case 0:
       	if ( !(window.arguments != null && window.arguments[0] != null && window.arguments[0].closeOnNoErrors == 1)) {
      		 reminderFox_upload_statusTxt(aStatus,aError);
      	}    	
      break;
    case -3:
      reminderFox_upload_statusTxt(reminderFox_getBundle().getString("rf.upload.sourceFileNotFound.label"),0);
		if ( reminderFox_upload_headless == REMINDER_FOX_UI_MODE_HEADLESS_SHOW_ERRORS) {
			var status =   (aError)?reminderFox_upload_getErrorMsg(aError):aStatus;
			alert( reminderFox_getBundle().getString("rf.add.network.status.msg.error") + ": " + status );
  		}         
      break;
    case 201:
      reminderFox_upload_statusTxt(reminderFox_getBundle().getString("rf.upload.created.label"),0);
		if ( reminderFox_upload_headless == REMINDER_FOX_UI_MODE_HEADLESS_SHOW_ERRORS) {
			var status =   (aError)?reminderFox_upload_getErrorMsg(aError):aStatus;
			// 201 means that the file was created successfully - we don't need to show this message - icalexchange, for 
			// instance, returns this code every time you write the file (I guess because it recreates it each time)
			//alert( "ReminderFox: " + status );
  		}         
      break;
    default:
     	 reminderFox_upload_statusTxt(aStatus,aError);
		if (reminderFox_upload_headless == REMINDER_FOX_UI_MODE_HEADLESS_SHOW_ERRORS) {
			var status = null;
			if (aError == -1) {
				status = aStatus;
			}
			else {
				(aError) ? reminderFox_upload_getErrorMsg(aError) : aStatus;
			}
			alert( reminderFox_getBundle().getString("rf.add.network.status.msg.error") + ": " + status );
  		}      
      return;
      break;
  }

//    if ( aError == 0 ) { 
      if ( reminderFox_upload_headless == REMINDER_FOX_UI_MODE_HEADLESS_SHOW_ALL_UI) {
		  reminderFox_upload_closeWindow();
  	  }

//  }


}

function reminderFox_upload_statusTxt(aStatus,aError)
{
  	  	if (reminderFox_upload_headless == REMINDER_FOX_UI_MODE_HEADLESS_SHOW_ALL_UI ) {
  			 document.getElementById("status").value =(aError)?reminderFox_upload_getErrorMsg(aError):aStatus;
  		}
  		else {
  			var value = (aError)?	reminderFox_upload_getErrorMsg(aError):aStatus;
			reminderFox_logMessageLevel("Upload (headless): " + new Date() + " " + value, REMINDER_FOX_LOG_LEVEL_FINE);
  		}	
}

function reminderFox_cancelUpload()
{
  gUploadService.cancel();
	close();
}


function reminderFox_upload_getErrorMsg(aStatus)
{
  if(aStatus==0)
    return reminderFox_getBundle().getString("rf.ok");;

  var status=aStatus % 0x804b0000;
  var error=reminderFox_getBundle().getString("rf.upload.unexpected.label");
  switch(status)
  {
    case 1:
      error=reminderFox_getBundle().getString("rf.upload.unexpected.label");
      break;
    case 2:
      error=reminderFox_getBundle().getString("rf.upload.usercancel.label");
      break;
	case 3:
      error=reminderFox_getBundle().getString("rf.upload.noPasswordSet.label");
      break;	  
    case 13:
      error=reminderFox_getBundle().getString("rf.upload.refused.label");
      break;
    case 14:
      error=reminderFox_getBundle().getString("rf.upload.netTimeout.label");
      break;
    case 16:
      error=reminderFox_getBundle().getString("rf.upload.netOffline.label");
      break;
    case 21:
      error=reminderFox_getBundle().getString("rf.upload.loginfailure.label");
      break;
    case 22:
      error=reminderFox_getBundle().getString("rf.upload.ftpcwd.label");
      break;
    case 23:
      error=reminderFox_getBundle().getString("rf.upload.ftppasv.label");
      break;
    case 24:
      error=reminderFox_getBundle().getString("rf.upload.ftppwd.label");
      break;
    case 25:
      error=reminderFox_getBundle().getString("rf.upload.ftplist.label");
      break;
    case 30:
      error=reminderFox_getBundle().getString("rf.upload.unknown.label");
      break;
    case 201:
      reminderFox_upload_statusTxt(reminderFox_getBundle().getString("rf.upload.created.label"),0);
      break;
    case 401:
      error=reminderFox_getBundle().getString("rf.upload.loginfailure.label");
      break;
    case 405:
      error=reminderFox_getBundle().getString("rf.upload.methodNotAllowed.label");
      break;
    case 409:
      error=reminderFox_getBundle().getString("rf.upload.DestFileNotDefined.label");
      break;
    default:
      error=reminderFox_getBundle().getString("rf.upload.unexpected.label");
      break;
  }

  var formatted= (aStatus<0x804b0000)?
          aStatus.toString(10) : "0x" + aStatus.toString(16).toUpperCase();
  return  error + " (" + formatted + ")\n";
}
